
class MeiyidaInfo extends AbstractPlugin {

  static BASE_URL = 'https://www.mydys1.com';

  async fetchWebsiteInfo() {
    const url = window.location.href;

    const parser = new DOMParser();
    const doc = parser.parseFromString(document.body.outerHTML, 'text/html');

    const playSources = [];

    const tabLists = doc.querySelectorAll('.module-play-list-content');
    const tabTitles = doc.querySelectorAll('.module-tab-items .module-tab-item');

    tabLists.forEach((tabList, index) => {
      const tabItems = tabList.querySelectorAll('.module-play-list-link');
      if(tabItems.length > 0) {
        const episodes = [];
        tabItems.forEach((tabItem) => {
          const episodeItem = new Episode();
          episodeItem.title = tabItem.textContent.trim();
          const href = tabItem.getAttribute('href');
          episodeItem.link = href.startsWith('/') ? `${MeiyidaInfo.BASE_URL}${href}` : href;
          episodes.push(episodeItem);
        })
        const title = tabTitles[index].textContent.trim();
        playSources.push(new Source({
          title: title,
          episodes: episodes
        }));
      }
    });

    const websiteInfo = new WebsiteInfo();
    websiteInfo.type = 'video';
    const titleElement = doc.querySelector('.module-info-heading h1');
    if(titleElement) {
      websiteInfo.title = titleElement.textContent.trim();
    }
    websiteInfo.link = url;
    websiteInfo.sources = playSources;

    const playRegex = /\/vodplay\//;
    if(playRegex.test(url)) {
      websiteInfo.playUrl = this.getPlayUrlFromBody(document.body.outerHTML);
      const curEp = doc.querySelector('.module-play-list-link.active');
      if(curEp) {
        const href = curEp.getAttribute('href');
        const curEpLink = href.startsWith('/') ? `${MeiyidaInfo.BASE_URL}${href}` : href;
        [websiteInfo.sourceIndex, websiteInfo.episodeIndex] = AbstractPlugin.findEpisode(playSources, curEpLink);
      }
    }

    return websiteInfo;
  }

  async fetchPlayUrlInfo(url) {
    const http_headers = {
      'User-Agent': MeiyidaInfo.DEFAULT_USER_AGENT,
      'Origin': MeiyidaInfo.BASE_URL,
    };
    const result = await doHttpRequestSync(url, { headers: http_headers });
    if(result.status !== 'success') {
      return null;
    }
    return this.getPlayUrlFromBody(result.body)
  }

  getPlayUrlFromBody(body) {
    const regex = /player_aaaa\s*=\s*(\{(?:[^{}]|{(?:[^{}]|{[^{}]*})*})*})/;
    const match = body.match(regex);
    if(!match) {
      return null;
    }

    try {
      const data = JSON.parse(match[1]);
      const playUrl = new PlayUrlInfo();
      playUrl.type = 'video';
      playUrl.urls = [decodeURIComponent(data['url'])];
      return playUrl;
    } catch (error) {
      return null;
    }
  }

}
Registry.registerClass("MeiyidaInfo", new MeiyidaInfo());